package com.gqz.patrol.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.gqz.common.core.domain.RequestForm;
import com.gqz.common.core.utils.poi.ExcelUtil;
import com.gqz.common.core.utils.query.QueryMapperUtil;
import com.gqz.patrol.app.entity.EnPatrolTaskEntity;
import com.gqz.patrol.entity.EnPatrolTaskElectricityEntity;
import com.gqz.patrol.mapper.EnPatrolTaskElectricityMapper;
import com.gqz.patrol.mapstruct.EnPatrolTaskElectricityMapstruct;
import com.gqz.patrol.service.IEnPatrolTaskElectricityService;
import com.gqz.patrol.vo.EnPatrolTaskElectricityVo;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;


/**
 * 电量采集信息表 ҵ���߼�ʵ�ֲ�ServiceImpl
 */
@Service
@Slf4j
public class EnPatrolTaskElectricityServiceImpl extends ServiceImpl<EnPatrolTaskElectricityMapper, EnPatrolTaskElectricityEntity> implements IEnPatrolTaskElectricityService {

    @Qualifier("enPatrolTaskElectricityMapstructImpl")
    @Autowired
    private EnPatrolTaskElectricityMapstruct mapstruct;

    @Override
    public List<EnPatrolTaskElectricityVo> getById(String id) {
        MPJLambdaWrapper<EnPatrolTaskElectricityEntity> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(EnPatrolTaskElectricityEntity::getId, id);
        queryWrapper.selectAll(EnPatrolTaskElectricityEntity.class);
        List<EnPatrolTaskElectricityEntity> entities = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(entities)) {
            return mapstruct.toVos(entities);
        }
        return new ArrayList<>();
    }

    @Override
    public Page<EnPatrolTaskElectricityVo> page(RequestForm<EnPatrolTaskElectricityVo> requestForm) {
        EnPatrolTaskElectricityEntity entity = mapstruct.toEntity(requestForm.getEntity());
        //拿到采集时间
        Date acqTime = entity.getAcqTime();
        Date acqTimeTo = entity.getAcqTimeTo();

        MPJLambdaWrapper<EnPatrolTaskElectricityEntity> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAs(EnPatrolTaskEntity::getId, "taskId");
        queryWrapper
                .selectAll(EnPatrolTaskElectricityEntity.class)
                .eq(StringUtils.isNotBlank(entity.getUnitId())
                        , EnPatrolTaskElectricityEntity::getUnitId, entity.getUnitId())
                .like(StringUtils.isNotBlank(entity.getUnitName())
                        , EnPatrolTaskElectricityEntity::getUnitName, entity.getUnitName())
                .eq(StringUtils.isNotBlank(entity.getEnergySiteId())
                        , EnPatrolTaskElectricityEntity::getEnergySiteId, entity.getEnergySiteId())
                .like(StringUtils.isNotBlank(entity.getEnergySiteName())
                        , EnPatrolTaskElectricityEntity::getEnergySiteName, entity.getEnergySiteName())
                .like(StringUtils.isNotBlank(entity.getElectricityMeterNo())
                        , EnPatrolTaskElectricityEntity::getElectricityMeterNo, entity.getElectricityMeterNo())
                .like(StringUtils.isNotBlank(entity.getElectricityMeterName())
                        , EnPatrolTaskElectricityEntity::getElectricityMeterName, entity.getElectricityMeterName())
                .like(StringUtils.isNotBlank(entity.getPowerDistName())
                        , EnPatrolTaskElectricityEntity::getPowerDistName, entity.getPowerDistName())
                .like(StringUtils.isNotBlank(entity.getElectricityMeterName())
                        , EnPatrolTaskElectricityEntity::getElectricityMeterName, entity.getElectricityMeterName())
                .like(StringUtils.isNotBlank(entity.getAcqPerson())
                        , EnPatrolTaskElectricityEntity::getAcqPerson, entity.getAcqPerson())
                .eq(EnPatrolTaskElectricityEntity::getDeleted, 0);

        if (entity.getAcqTime() != null && !"".equals(entity.getAcqTime())) {
            queryWrapper.ge(EnPatrolTaskElectricityEntity::getAcqTime, entity.getAcqTime());
        }
        if (entity.getAcqTimeTo() != null && !"".equals(entity.getAcqTimeTo())) {
            queryWrapper.le(EnPatrolTaskElectricityEntity::getAcqTime, entity.getAcqTimeTo());
        }


        queryWrapper.innerJoin(EnPatrolTaskEntity.class, EnPatrolTaskEntity::getTaskNo, EnPatrolTaskElectricityEntity::getTaskNo);

        queryWrapper.orderByDesc(
                EnPatrolTaskElectricityEntity::getEnergySiteName,
                EnPatrolTaskElectricityEntity::getPowerDistName,
                EnPatrolTaskElectricityEntity::getAcqTime
        );
        Page<EnPatrolTaskElectricityVo> page = Page.of(requestForm.getPageNo(), requestForm.getPageSize());
        //page = baseMapper.selectPage(page, queryWrapper);
        IPage<EnPatrolTaskElectricityVo> iPage = baseMapper.selectJoinPage(page, EnPatrolTaskElectricityVo.class, queryWrapper);
        List<EnPatrolTaskElectricityVo> records = iPage.getRecords();
        page.setRecords(records);
        page.setTotal(iPage.getTotal());
        return page;
    }

    @Override
    public Long count(RequestForm<EnPatrolTaskElectricityVo> requestForm) {
        EnPatrolTaskElectricityEntity entity = mapstruct.toEntity(requestForm.getEntity());
        MPJLambdaWrapper<EnPatrolTaskElectricityEntity> queryWrapper = QueryMapperUtil.initQueryWrapper(entity, requestForm);
        queryWrapper.select(EnPatrolTaskElectricityEntity::getId);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public int insert(List<EnPatrolTaskElectricityVo> forms) {
        List<EnPatrolTaskElectricityEntity> entitys = mapstruct.toEntitys(forms);
        int result = 0;
        for (int i = 0, size = entitys.size(); i < size; i++) {
            EnPatrolTaskElectricityEntity entity = entitys.get(i);
            result += baseMapper.insert(entity);
        }
        return result;
    }

    @Override
    public int update(List<EnPatrolTaskElectricityVo> forms) {
        List<EnPatrolTaskElectricityEntity> entitys = mapstruct.toEntitys(forms);
        int result = 0;
        for (int i = 0, size = entitys.size(); i < size; i++) {
            EnPatrolTaskElectricityEntity entity = entitys.get(i);
            result += baseMapper.updateById(entity);
        }
        return result;
    }

    @Override
    public List<EnPatrolTaskElectricityVo> getByTaskNo(String taskNo) {
        Optional.ofNullable(taskNo).orElseThrow(() -> new RuntimeException("工单编号不可为空！"));
        LambdaQueryWrapper<EnPatrolTaskElectricityEntity> queryWrapper = Wrappers
                .lambdaQuery(EnPatrolTaskElectricityEntity.class)
                .select(field -> true)
                .eq(EnPatrolTaskElectricityEntity::getTaskNo, taskNo)
                .eq(EnPatrolTaskElectricityEntity::getDeleted, 0)
                .orderByDesc(
                        EnPatrolTaskElectricityEntity::getEnergySiteName,
                        EnPatrolTaskElectricityEntity::getPowerDistName,
                        EnPatrolTaskElectricityEntity::getAcqTime
                );
        List<EnPatrolTaskElectricityEntity> electricityEntities = list(queryWrapper);
        return mapstruct.toVos(electricityEntities);
    }

    /**
     * 导出电能表采集Excel
     *
     * @param resp
     * @param requestForm
     */
    @Override
    public void exportExcel(HttpServletResponse resp, RequestForm<EnPatrolTaskElectricityVo> requestForm) {
        //设置信息头，告诉浏览器内容为excel类型
        resp.setHeader("content-Type", "application/vnd.ms-excel");
        //文件名称
        String fileName = "电能采集信息.xls";
        //sheet名称
        String sheetName = "电能采集信息列表";
        fileName = new String(fileName.getBytes(), StandardCharsets.UTF_8);
        //设置下载名称
        resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        if (requestForm.getPageSize() < 1000L) {
            requestForm.setPageSize(1000L);
        }
        //获取到业务数据
        Page<EnPatrolTaskElectricityVo> page = this.page(requestForm);
        //导入excel
        new ExcelUtil<>(EnPatrolTaskElectricityVo.class).exportExcel(resp, page.getRecords(), sheetName);
    }
}
